// 模拟用户数据存储
let mockUsers = JSON.parse(localStorage.getItem('mockUsers')) || [
  {
    id: 1,
    username: 'testuser',
    password: '123456', // 实际项目中应该加密存储
    email: 'test@example.com',
    avatar: 'https://picsum.photos/id/237/200/200',
    createdAt: new Date().toISOString(),
    statistics: {
      videos: 12,
      followers: 258,
      following: 120,
      likes: 1234
    }
  }
];

// 保存用户数据到 localStorage
const saveUsers = () => {
  localStorage.setItem('mockUsers', JSON.stringify(mockUsers));
};

// 注册功能
export const register = async (userData) => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  // 检查用户名是否已存在
  const existingUser = mockUsers.find(user => 
    user.username === userData.username || user.email === userData.email
  );
  
  if (existingUser) {
    throw new Error('用户名或邮箱已存在');
  }
  
  // 创建新用户
  const newUser = {
    id: Date.now(),
    username: userData.username,
    password: userData.password, // 实际项目中应该加密存储
    email: userData.email,
    avatar: `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/200/200`,
    createdAt: new Date().toISOString(),
    statistics: {
      videos: 0,
      followers: 0,
      following: 0,
      likes: 0
    }
  };
  
  mockUsers.push(newUser);
  saveUsers();
  
  return true;
};

// 登录功能
export const login = async (username, password) => {
  // 减少模拟网络延迟时间，提升登录体验
  await new Promise(resolve => setTimeout(resolve, 300));
  
  // 查找用户
  const user = mockUsers.find(u => u.username === username && u.password === password);
  
  if (user) {
    // 保存登录状态到 localStorage
    localStorage.setItem('currentUser', JSON.stringify({
      id: user.id,
      username: user.username,
      email: user.email,
      avatar: user.avatar
    }));
    return true;
  }
  
  return false;
};

// 获取当前登录用户
export const getCurrentUser = () => {
  const userStr = localStorage.getItem('currentUser');
  return userStr ? JSON.parse(userStr) : null;
};

// 登出功能
export const logout = () => {
  localStorage.removeItem('currentUser');
};

// 获取用户详细信息
export const getUserProfile = (userId) => {
  return mockUsers.find(user => user.id === userId) || null;
};

// 更新用户信息
export const updateUserProfile = (userId, updateData) => {
  const userIndex = mockUsers.findIndex(user => user.id === userId);
  
  if (userIndex !== -1) {
    // 更新用户信息
    mockUsers[userIndex] = {
      ...mockUsers[userIndex],
      ...updateData
    };
    
    // 如果更新了当前登录用户的信息，同步更新localStorage中的数据
    const currentUser = getCurrentUser();
    if (currentUser && currentUser.id === userId) {
      localStorage.setItem('currentUser', JSON.stringify({
        ...currentUser,
        username: updateData.username || currentUser.username,
        avatar: updateData.avatar || currentUser.avatar,
        email: updateData.email || currentUser.email
      }));
    }
    
    saveUsers();
    return true;
  }
  
  return false;
};

// 检查是否已登录
export const isLoggedIn = () => {
  return !!localStorage.getItem('currentUser');
};